package com.dwj.auto.comment.common.wechat.handler;

import com.dwj.auto.comment.common.response.Response;
import com.dwj.auto.comment.dao.entity.SubscribeUser;
import com.dwj.auto.comment.dao.entity.User;
import com.dwj.auto.comment.model.wechat.WxMessage;
import com.dwj.auto.comment.service.ISubscribeUserService;
import com.dwj.auto.comment.service.IUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName ResetPasswordListener
 * @Description 重置密码监听者
 * @Author dwjian
 * @Date 2020/12/26 19:20
 */
@Component
public class ResetPasswordHandler extends WxTextMessageHandler implements WxMessageHandler {

    @Resource
    private IUserService userService;
    @Resource
    private ISubscribeUserService subscribeUserService;

    @Override
    public String dealMessage(WxMessage message) {
        //重置密码
        String regex = "^(重置密码([：:]))[0-9A-Za-z]{6,}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(message.getContent());
        if (matcher.find()) {
            SubscribeUser localSubscribeUser = subscribeUserService.lambdaQuery().eq(SubscribeUser::getOpenId, message.getOpenId()).eq(SubscribeUser::getIsDel, 0).one();
            if (localSubscribeUser == null) {
                return "你还未注册，请发送“注册“获取账号。";
            } else {
                String newPassword = message.getContent().replaceAll("(重置密码([：:]))", "");
                Response<Boolean> response = userService.resetPassword(localSubscribeUser.getUserId(), newPassword);
                if (response.isOK() && response.getData()) {
                    User user = userService.lambdaQuery().eq(User::getId, localSubscribeUser.getUserId()).eq(User::getIsDel, 0).one();
                    return "您的账号：" + user.getUsername() + "\n密码已重置为：" + newPassword + "\n请妥善保管。";
                } else {
                    return "重置失败，请稍后再试！";
                }
            }
        } else {
            return "密码格式有误，请检查后再试！\n正确格式为“重置密码：新密码”。\n例如“重置密码：123456“\n注意：新密码必须由六位数字或字母组成。";
        }
    }
}
